public class HashBuck {
    static class Node {
        public int key;
        public int val;
        public Node(int key, int val) {
            this.key = key;
            this.val = val;
        }
        public Node next;
    }
    public Node[] array = new Node[10];

    public int useSize;

    public static final double Load_FACTOR = 0.75;

    public void push(int key, int val) {
        //1.找到位置
        int index = key % array.length;
        //2.检查index位置是否位空
        Node node = new Node(key,val);
        Node cur = array[index];
        /*if (cur == null) {
            //数组index为空时则直接插入
            array[index] = node;
            useSize++;
            return;
        }*/   //方便理解,头插法包含了这一步，写出来是为了方便理解4头插法的使用
        //3.遍历数组判断是否需要更新val
        while (cur != null) {
            //如果遇到相同的key则更新val
            if (cur.key == key) {
                cur.val = val;
                return;
            }
            cur = cur.next;
        }

        //4.使用头插法
        node.next = array[index];
        array[index] = node;
        useSize++;

        //5.检查负载因子是否过大（>=0.75），大于则扩大两倍.
        if (doLoadFactor() >= 0.75) {
            //负载因子过大，重新哈希（重新排列）
            reSize();
        }
    }
    private void reSize() {

        //重新写一个数组
        Node[] newArray = new Node[2*array.length];

        //重新哈希
        for (int i = 0; i < array.length; i++) {
            Node node = array[i];
            while (node != null) {
                int index = node.key % newArray.length;
                //1.判断是否是第一个插入
                if (newArray[index] == null) {
                    newArray[index] = node;
                    break;
                }
                //2.不是第一个插入则头插法,并插入新数组
                Node nodeNext = node.next;//记录node的下一个位置
                node.next = newArray[index];
                newArray[index] = node;

                node = nodeNext;
            }
        }

        //数据传到原数组 array
        array = newArray;
    }
    private double doLoadFactor() {
        return useSize*1.0/array.length;
    }

    //根据key获取val
    public int get(int key) {
        //找到位置
        int index = key % array.length;
        Node node = array[index];
        //遍历数组
        while (node != null) {
            if (node.key == key) {
                return node.val;
            }
            node = node.next;
        }
        return -1;
    }

}
